/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package session;

import entity.CustomerOrder;
import cart.ShoppingCart;
import entity.Customer;
import java.util.List;
import java.util.Random;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Lisha
 */
@Stateless
public class CustomerOrderFacade extends AbstractFacade<CustomerOrder> {
    @PersistenceContext(unitName = "emangaPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CustomerOrderFacade() {
        super(CustomerOrder.class);
    }
    
    public void insertCustomerOrder(HttpServletRequest request, ShoppingCart cart, int customerId)
    {        
        Random random = new Random();
        int confirmationNumber = random.nextInt(999999999);
        String deliveryType = request.getParameter("delivery");
        String deliveryCost;
        String deliveryTime;
        if(deliveryType.equals("standard"))
        {
            deliveryCost = "2.00";
            deliveryTime = "14";
            cart.calculateTotal("2.00");
        }
        else if(deliveryType.equals("express"))
        {
            deliveryCost = "5.00";
            deliveryTime = "7";
            cart.calculateTotal("5.00");
        }
        else
        {
            deliveryCost = "9.00";
            deliveryTime = "1";
            cart.calculateTotal("9.00");
        }
        em.createNativeQuery("INSERT INTO customer_order VALUES ('0', " + cart.getTotal() + ", '" + deliveryType + "', " + deliveryCost + ", " + deliveryTime + ", '" + request.getParameter("address").replaceAll("'", "\'\'") + "', '" + request.getParameter("card_type") + "', " + request.getParameter("card_number") + ", '" + request.getParameter("card_expiration") + "', " + request.getParameter("card_crypt") + ", " + confirmationNumber + ", NOW(), " + customerId + ")").executeUpdate();
    }
    
    public CustomerOrder findByLastCustomerId(Integer i) {
        Query q = em.createNamedQuery("CustomerOrder.findByLastCustomerId");
        q.setParameter("customerId", i);
        return (CustomerOrder)q.getSingleResult();
    }
    
    public List<CustomerOrder> findByCustomerId(Integer i) {
        Query q = em.createNamedQuery("CustomerOrder.findByCustomerId");
        q.setParameter("customerId", i);
        return q.getResultList();
    }

}
